<template>
  <div class="family-info">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>

      <!-- 加载中 -->
      <div v-if="loading" class="loading-overlay">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>加载中...</span>
      </div>

      <!-- 信息展示 -->
      <div v-else class="profile-content">
        <!-- 展示模式 -->
        <div class="info-display" v-if="!isEditing">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="头像">
              <div style="display: flex; justify-content: center;">
                <el-avatar :size="60" :src="currentUser.avatarUrl || defaultAvatar" />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="用户名">{{ currentUser.username || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="真实姓名">{{ currentUser.realName || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ currentUser.phone || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentUser.email || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ formatGender(currentUser.gender) }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ formatDate(currentUser.birthDate) || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ currentUser.idCard || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ currentUser.address || '未设置' }}</el-descriptions-item>
          </el-descriptions>

          <div class="action-buttons">
            <el-button type="primary" @click="startEditing">修改信息</el-button>
            <el-button type="warning" @click="showPasswordDialog = true">修改密码</el-button>
          </div>
        </div>

        <!-- 编辑模式 -->
        <div class="info-edit" v-else>
          <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editFormRef">
            <el-form-item label="头像">
              <el-upload
                  class="avatar-uploader"
                  :action="`${BASE_URL}/api/v1/family_user/avatar?userId=${currentUser.userId}`"
                  name="avatarFile"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeImageUpload"
              >
                <img v-if="editForm.avatarUrl" :src="editForm.avatarUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="editForm.realName" placeholder="请输入真实姓名"/>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" placeholder="请输入手机号"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" placeholder="请输入邮箱"/>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" placeholder="请选择性别">
                <el-option label="未知" :value="0"/>
                <el-option label="男" :value="1"/>
                <el-option label="女" :value="2"/>
              </el-select>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                  v-model="editForm.birthDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="editForm.idCard" placeholder="请输入身份证号"/>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="editForm.address" placeholder="请输入地址"/>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitEdit">保存</el-button>
              <el-button @click="cancelEditing">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="30%">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordChange">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import axios from 'axios'
import {Loading, Plus} from '@element-plus/icons-vue'
import { inject } from 'vue'


const BASE_URL = 'http://localhost:8080'


// 使用注入的 currentUser 和 refreshUserInfo
const currentUser = inject('currentUser')
const refreshUserInfo = inject('refreshUserInfo')
// 用户信息
// const currentUser = ref({
//   userId: null,
//   username: '',
//   realName: '',
//   phone: '',
//   email: '',
//   gender: 0,
//   birthDate: '',
//   idCard: '',
//   address: '',
//   avatarUrl: ''
// })

const defaultAvatar = new URL('@/assets/images/default-avatar.png', import.meta.url).href

// 编辑状态
const isEditing = ref(false)
const loading = ref(true)

// 表单引用
const editFormRef = ref()
const passwordFormRef = ref()

// 表单数据
const editForm = ref({...currentUser.value})
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 头像上传
const avatarUploadUrl = `${BASE_URL}/api/v1/family_user/avatar`
const headers = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 对话框
const showPasswordDialog = ref(false)

// 表单验证
const editRules = {
  realName: [{required: true, message: '请输入真实姓名', trigger: 'blur'}],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur'}
  ],
  email: [{type: 'email', message: '邮箱格式错误', trigger: 'blur'}],
  idCard: [{pattern: /^\d{17}[\dXx]$/, message: '身份证号格式错误', trigger: 'blur'}]
}

const passwordRules = {
  oldPassword: [{required: true, message: '请输入旧密码', trigger: 'blur'}],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 18, message: '密码长度6-18位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请再次输入新密码', trigger: 'blur'},
    {
      validator: (_, value, callback) =>
          value === passwordForm.value.newPassword ? callback() : callback(new Error('两次密码不一致')),
      trigger: 'blur'
    }
  ]
}

// 工具函数
const formatGender = (gender) => {
  return gender === 1 ? '男' : gender === 2 ? '女' : '未知'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toISOString().split('T')[0]
}

// 上传头像
const handleAvatarSuccess = (response) => {
  if (response && response.data) {
    const newAvatar = response.data + '?t=' + Date.now()
    editForm.value.avatarUrl = newAvatar
    currentUser.value.avatarUrl = newAvatar // 直接更新注入的 currentUser
    ElMessage.success('头像上传成功')
    refreshUserInfo?.()
  }
}

const beforeImageUpload = (file) => {
  const isType = ['image/jpeg', 'image/png'].includes(file.type)
  const isSize = file.size / 1024 / 1024 < 2
  if (!isType) ElMessage.error('仅支持 JPG/PNG')
  if (!isSize) ElMessage.error('图片大小不能超过2MB')
  return isType && isSize
}

// 编辑
const startEditing = () => {
  editForm.value = {...currentUser.value}
  isEditing.value = true
}

const cancelEditing = () => {
  isEditing.value = false
}

const submitEdit = async () => {
  try {
    await editFormRef.value.validate()
    const response = await axios.post(
        `${BASE_URL}/api/v1/family_user/info`,
        {...editForm.value, userId: currentUser.value.userId},
        {headers: {Authorization: `Bearer ${localStorage.getItem('token')}`}}
    )
    if (response.data.code === 200 || response.data.code === 2000) {
      ElMessage.success('更新成功')
      Object.assign(currentUser.value, editForm.value)
      isEditing.value = false
    } else {
      ElMessage.error(response.data.msg || '更新失败')
    }
  } catch (e) {
    ElMessage.error('更新失败，请稍后重试')
  }
}

const submitPasswordChange = async () => {
  try {
    await passwordFormRef.value.validate()
    const response = await axios.post(
        `${BASE_URL}/api/v1/family_user/password`,
        {...passwordForm.value, userId: currentUser.value.userId},
        {headers: {Authorization: `Bearer ${localStorage.getItem('token')}`}}
    )
    if (response.data.code === 200 || response.data.code === 2000) {
      ElMessage.success('密码修改成功')
      showPasswordDialog.value = false
      passwordFormRef.value.resetFields()
    } else {
      ElMessage.error(response.data.msg || '修改失败')
    }
  } catch (e) {
    ElMessage.error('修改失败，请稍后重试')
  }
}

onMounted(() => {
  loading.value = false
})
</script>

<style scoped>
.loading-overlay {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  color: #666;
}

.loading-icon {
  font-size: 36px;
  margin-bottom: 10px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.family-info {
  max-width: 100%;
  margin: 20px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>